from google.appengine.ext import db
from google.appengine.ext import webapp
import wsgiref.handlers

from myuser import User
from page import Page
from write import WriteRank

from urlparse import urlparse
import string
#import float



class ReadRank(webapp.RequestHandler):  
  def get(self):	
	url = self.request.get('url')	
	callback = self.request.get('callback')	
	url_p = urlparse(url)		
	protocol,domain = url_p[:2]
	back_pos = self.request.get('back_pos')
	
	if url == '' or domain == '':
		self.response.out.write("%s({\"res\":\"err\",\"rank\":\"0\",\"count\":\"0\",\"back_pos\":\"%s\"})" % (callback,back_pos))
		return
    #check user
	user = db.GqlQuery("SELECT * FROM User WHERE domain=:1 ORDER BY date DESC LIMIT 1",domain)
	
	#if user absent, create a new user
	if user.count() < 1:
		user = User()
		user.domain = domain
		user.name = "unknown"
		user.put()
	else:
		user = user.fetch(1).pop()

	#match the page url
	page = db.GqlQuery("SELECT * FROM Page WHERE url=:1 ORDER BY date DESC LIMIT 1",url)
	#if page not found , create a new page
	if page.count() < 1:
		page = Page()
		page.url = url
		page.count = 0
		page.score = 0.0
		page.user_id = user.key()
		page.put()
	else:
		page = page.fetch(1).pop()	
	
	#return the page rank
	self.response.headers['Content-Type'] = 'application/x-javascript'
	
	self.response.out.write("%s({\"res\":\"succ\",\"rank\":\"%f\",\"count\":\"%i\",\"back_pos\":\"%s\",\"url\":\"%s\"})" % (callback,page.score,page.count,back_pos,url))
	
	
def main():
  application = webapp.WSGIApplication(
                                       [('/read', ReadRank),('/write', WriteRank)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)
  
if __name__ == "__main__":
	main()
